<template>
  <div class="consumer-page activity-list-page">
    <el-breadcrumb class="breadcrumb page-title" separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">Activities</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="container-padding">
      <!--serchBox-->
      <div class="search-box">
        <el-form :inline="true" label-position="top" :model="searchForm" size="mini" ref="ruleForm"
                 class="demo-ruleForm main-search-box">

          <el-form-item label="Status" style="width: 200px;margin-right: 10px">
            <el-select style="width: 200px" v-model="searchForm.statusId" placeholder="">
              <el-option v-for="i in statusOption" :key="i.value" :label="i.label" :value="i.value"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="Restaurant Name" style="width: 200px;">
            <el-input v-model="searchForm.restaurantName" placeholder=""></el-input>
          </el-form-item>


          <el-form-item style="margin-top: 37px;margin-left: 30px;">
            <el-button @click="getList(1)">Search</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--list-->
      <div class="list-items-box">
        <!--表格-->
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          border
          @selection-change="handleSelectionChange"
          style="width: 100%">

          <el-table-column
            prop="Property"
            label="Edit"
            align="center"
            width="100">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="editActivity(scope.row.id, scope.row.restaurantId, scope.row)">Edit
              </el-button>
            </template>
          </el-table-column>

          <!--ID-->
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            min-width="100">
          </el-table-column>

          <!--Status-->
          <el-table-column
            prop="status"
            label="Status"
            align="center"
            min-width="100">
            <template slot-scope="scope">
              <p>{{getStatus(scope.row.status)}}</p>
            </template>
          </el-table-column>

          <!--Activity Date-->
          <el-table-column
            prop="activityTime"
            label="Activity Date"
            align="center"
            min-width="120">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.activityTime, 'Date')}}</p>
            </template>
          </el-table-column>

          <!--Activity Type-->
          <el-table-column
            prop="discount"
            label="Activity Type"
            align="center"
            min-width="120">
            <template slot-scope="scope">
              <p>{{getActivityType(scope.row.activityType)}}</p>
            </template>
          </el-table-column>

          <!--Objective-->
          <el-table-column
            prop="people"
            label="Objective"
            align="center"
            min-width="150">
            <template slot-scope="scope">
              <p>{{getObjective(scope.row.objectives, scope.row.otherObjectives)}}</p>
            </template>
          </el-table-column>

          <!--Result-->
          <el-table-column
            prop="result"
            label="Result"
            align="center"
            min-width="120">
          </el-table-column>

          <!--Created Date-->
          <el-table-column
            prop="status"
            label="Created Date"
            align="center"
            min-width="140">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.createDate, 'listedDate')}}</p>
            </template>
          </el-table-column>

          <!--Created By-->
          <el-table-column
            prop="createBy"
            label="Created By"
            align="center"
            min-width="120">
          </el-table-column>

          <!--Updated Date-->
          <el-table-column
            prop="consumerName"
            label="Updated Date"
            align="center"
            min-width="140">
            <template slot-scope="scope">
              <p>{{dateFormat(scope.row.updateDate, 'listedDate')}}</p>
            </template>
          </el-table-column>

          <!--Updated By-->
          <el-table-column
            prop="updateBy"
            label="Updated By"
            align="center"
            min-width="120">
          </el-table-column>

        </el-table>
        <!--分页-->
        <div class="block" style="margin-top: 15px;text-align: center;">
          <el-pagination
            @size-change="handleChangeSize"
            @current-change="handleChangePage"
            :current-page="pageData.pageNo"
            :page-size="pageData.pageSize"
            :page-sizes="[10, 20, 50, 100, 500]"
            :page-count="pageInfo.totalPages"
            :total="pageInfo.totalCount"
            layout="total, prev, pager, next, jumper, sizes">
          </el-pagination>
        </div>
      </div>
    </div>


    <el-dialog title="Edit" :visible.sync="dialogFormVisible">
      <el-form :inline="true" label-position="top" :model="editForm"  ref="editForm" :rules="editRules" size="mini">
        <el-row :gutter="20">
          <el-col>
            <el-form-item :label="$t('m.Status')" style="width: 200px;" prop="statusId">
              <el-select  v-model="editForm.statusId" placeholder="">
                <el-option v-for="rg in status" :key="rg.value" :label="rg.text" :value="rg.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="Activity Time" style="width: 200px;" prop="date">
              <el-date-picker v-model="editForm.date" style="width:200px;" type="date" placeholder=""></el-date-picker>
            </el-form-item>
            <el-form-item label="Activity Type" style="width: 200px;" prop="activityTypeId">
              <el-select style="width: 200px" v-model="editForm.activityTypeId" placeholder="">
                <el-option v-for="i in activityType" :key="i.value" :label="i.text" :value="i.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="Objective" prop="type">
              <div>
                <el-checkbox-group v-model="editForm.type">
                  <el-checkbox label="1" name="type" style="margin-right: 30px">Introduction</el-checkbox>
                  <el-checkbox label="2" name="type">Make appointment</el-checkbox>
                  <el-checkbox label="3" name="type">Software installation</el-checkbox>
                  <el-checkbox label="4" name="type">Training</el-checkbox>
                  <el-checkbox label="5" name="type">Software troubleshooting</el-checkbox>
                  <el-checkbox label="6" name="type">Complaint</el-checkbox>
                  <el-checkbox label="8" name="type">Data update</el-checkbox>
                  <div class="other" style="width: 300px">
                    <el-checkbox label="7" name="type">Others</el-checkbox>
                    <el-input
                      type="textarea"
                      :rows="4"
                      placeholder=""
                      v-model="editForm.otherObjectives">
                    </el-input>
                  </div>

                </el-checkbox-group>
              </div>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="Result" style="width: 300px;">
              <el-input
                type="textarea"
                :rows="4"
                placeholder=""
                v-model="editForm.result">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-button type="warning" @click="editSave()" size="medium">Save</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>

  import {activityList, newActivity} from '../../api/zxy_api.js'
  import qs from 'qs';

  export default {
    name: 'bookings',
    data() {
      return {
        searchForm: {
          statusId: '',
          restaurantName: ''
        },
        statusOption: [{
          label: 'Active',
          value: 1
        }, {
          label: 'Deleted',
          value: 2
        }],
        pageData: {
          pageNum: 1,
          pageSize: 10,
        },
        pageInfo: {
          totalCount: 0,
          totalPages: 0
        },
        activityTypeOption: [
          {
            value: 1,
            text: "Call"
          },
          {
            value: 2,
            text: "Visit"
          },
          {
            value: 3,
            text: "Received call"
          },
        ],
        dialogFormVisible: false,
        editForm: {
          statusId: null,
          date: null,
          activityTypeId: null,
          type: [],
          result: '',
          otherObjectives: '',
          restaurantId: '',
          id: null
        },
        status: [
          { "value": 1, "text": "Active"},
          { "value": 2, "text": "Deleted"}
        ],
        objective: [
          { "value": 1, "text": "Introduction"},
          { "value": 2, "text": "Make appointment"},
          { "value": 3, "text": "Software installation"},
          { "value": 4, "text": "Training"},
          { "value": 5, "text": "Software Troubleshooting"},
          { "value": 6, "text": "Complaint"},
          { "value": 8, "text": "Data update"},
          { "value": 7, "text": "Others"},
        ],
        activityType: [
          { "value": 1, "text": "Call"},
          { "value": 2, "text": "Visit"},
          { "value": 3, "text": "Received call"},
        ],
        editRules: {
          statusId: [
            {required: true, message: 'please select', trigger: 'change'}
          ],
          activityTypeId: [
            {required: true, message: 'Please Select', trigger: 'change'}
          ],
          date: [
            {type: 'date', required: true, message: 'Please Select', trigger: 'change'}
          ],
          type: [
            {type: 'array', required: true, message: 'Please Select', trigger: 'change'}
          ],
        },
        tableLoading: true,
        tableData: [],
      }
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val
        // [{row当前所有数据，developmentId}]
      },
      handleChangeSize(val) {
        this.pageData.pageSize = parseInt(val)
        this.pageData.pageNum = 1
        this.getList()
      },
      handleChangePage(val) {
        this.pageData.pageNum = val
        this.getList()
      },
      dateFormat(value, str) {
        var date = new Date(value)
        var Y = date.getFullYear()
        var m = date.getMonth() + 1
        var d = date.getDate()
        var H = date.getHours()
        var i = date.getMinutes()
        var s = date.getSeconds()
        if (m < 10) {
          m = '0' + m
        }
        if (d < 10) {
          d = '0' + d
        }
        if (H < 10) {
          H = '0' + H
        }
        if (i < 10) {
          i = '0' + i
        }
        if (s < 10) {
          s = '0' + s
        }
        if (str == 'listedDate') {
          var t = Y + '-' + m + '-' + d + '  ' + H + ':' + i + ':' + s
          return t
        }
        if (str == 'Date') {
          var tDate = d + '-' + m + '-' + Y
          return tDate;
        }
        if (str == 'made') {
          var amOrpm = '';
          if (H > 12) {
            amOrpm = ' pm'
          } else {
            amOrpm = ' am'
          }
          var tMade = d + '-' + m + '-' + Y + '  ' + H + ':' + i + amOrpm
          return tMade;
        }
        else if('editactivity'){
          var es =  Y  + '-' + m + '-'  + d
          return es
        }
        else {
          var ts = m + '-' + Y
          return ts
        }
      },
      getDay(day) {
        var val = '';
        // 0-6 递增
        switch (day) {
          case 0 :
            val = 'Monday';
            break;
          case 1 :
            val = 'Tuesday';
            break;
          case 2 :
            val = 'Wednesday';
            break;
          case 3 :
            val = 'Tuesday';
            break;
          case 4 :
            val = 'Friday';
            break;
          case 5 :
            val = 'Saturday';
            break;
          case 6 :
            val = 'Sunday';
            break;
        }
        return val;
      },
      getTime(timeFlag, timeHour, timeMinute) {
        // 0:am  1:pm
        if (timeFlag == 0) {
          return timeHour + '.' + timeMinute + ' am'
        } else {
          return timeHour + '.' + timeMinute + ' pm'
        }
      },
      getStatus(value) {
        if (value == 1) {
          return 'Active';
        } else if (value == 2) {
          return 'Deleted';
        }
      },
      getActivityType(value) {
        if (value == 1) {
          return 'Call'
        } else if (value == 2) {
          return 'Visit'
        } else if (value == 3) {
          return 'Received call'
        }
      },
      getObjective(objective, other) {
        if (objective) {
          let arr = objective.split(",");
          let str = '';
          for (let i = 0; i < arr.length; i++) {
            switch (Number(arr[i])) {
              case 1:
                str += 'Introduction, ';
                break;
              case 2:
                str += 'Make appointmen, ';
                break;
              case 3:
                str += 'Software installation, ';
                break;
              case 4:
                str += 'Training, ';
                break;
              case 5:
                str += 'Software Troubleshooting, ';
                break;
              case 6:
                str += 'Complaint, ';
                break;
              case 7:
                str += 'Others:' + other + ', ';
                break;
              case 8:
                str += 'Data update, ';
                break;
            }
          }

          str = str.substring(0, str.lastIndexOf(','))

          return str;
        }
      },
      // message alert 用于前端错误提示信息
      messageToastErr (msg) {
        this.$message({
          showClose: true,
          message: msg,
          duration: 5000,
          type: 'error'
        })
      },
      // 编辑modal
      editActivity(id, restaurantId, row){
        // 打开modal
        this.dialogFormVisible = true;

        // 请求数据
        let objectives = []
        if (row.objectives) {
          objectives = row.objectives.split(",")
        }

        this.editForm.statusId = row.status
        this.editForm.activityTypeId = row.activityType
        this.editForm.date = new Date(row.activityTime)
        this.editForm.type = objectives
        this.editForm.otherObjectives = row.otherObjectives
        this.editForm.result = row.result
        this.editForm.id = row.id
        this.editForm.restaurantId = row.restaurantId

      },
      editSave() {
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            this.dialogFormVisible = false
            let editForm = {
              restaurantId: this.editForm.restaurantId,
              status: this.editForm.statusId,
              activityTime: this.editForm.date ? this.dateFormat(this.editForm.date, 'editactivity') : '',
              activityType: this.editForm.activityTypeId,
              objectives: this.editForm.type ? this.editForm.type.join(',') : '',
              result: this.editForm.result,
              id: this.editForm.id,
            };
            if (this.editForm.type) {
              this.editForm.type.forEach((value, i, arr) => {
                if (value == 7) {
                  editForm.otherObjectives = this.editForm.otherObjectives;
                }
              })
            }
            editForm = qs.stringify(editForm)
            newActivity(editForm).then((res) => {
              console.log(res)
              if (res) {
                if (res.data.errorID == 0) {
                  this.getList()
                }
              }

            }).catch((e) => {
              console.log(e)
              this.messageToastErr('error,please refresh the page later')
            })
          } else {
            this.messageToastErr('error submit!!')
            return false;
          }
        });
      },
      getList(pageNum) {

        this.tableLoading = true;

        if (pageNum == 1) {
          this.pageData.pageNum = 1;
        }

        let searchForm = {
          status: this.searchForm.statusId || '',
          restaurantName: this.searchForm.restaurantName || ''
        };

        qs.stringify(searchForm)

        activityList(Object.assign(searchForm, this.pageData)).then((res) => {

          this.tableData = res.data.list || []

          // 分页信息配置
          this.pageInfo.totalPages = res.data.pages
          this.pageInfo.totalCount = res.data.total

          this.tableLoading = false;

        }).catch((e) => {
          console.log(e)
          this.tableLoading = false;
        })
      },
    },
    mounted() {
      this.getList()
    }
  }
</script>


<style>
  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px !important;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .page-title {
    padding: 20px 40px;
    border-bottom: 1px solid #e6e6e6;
    font-size: 20px;
  }

  .search-box {
    position: relative;
    /*padding-top: 20px;*/
    border-bottom: 1px solid #eee;
  }

  .line-form {
    border-top: 1px solid #eee;
  }

  .more-box, .list-items-box {
    padding-top: 20px;
    padding-bottom: 10px;
  }

  .list-items-box {
    /*margin-right: 10%;*/
  }

  .list-items-box .el-form--inline.el-form--label-top .el-form-item__content {
    display: inline-block;
  }

  .change-status {
    font-size: 14px;
    margin-right: 10px;
  }

  .options {
    padding: 0px 0 20px 0;
  }

  .container-padding {
    padding: 0 40px;
  }

  .list-notes {
    display: -webkit-box;
    -webkit-line-clamp: 4;
    -webkit-box-orient: vertical;
    overflow: hidden;
    line-height: 1.5;
  }

  .new-user-dialog .el-form-item {
    margin-bottom: 0 !important;
  }

  .activity-list-page .el-checkbox + .el-checkbox {
    margin-left: 0 !important;
    margin-right: 30px !important;
  }
</style>
